package com.yc.testupload.controller;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.yc.testupload.util.DatabaseUtil;

@WebServlet("/api/categories")
public class CategoryServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("application/json;charset=UTF-8");
        response.setHeader("Access-Control-Allow-Origin", "*"); // 允许跨域访问
        PrintWriter out = response.getWriter();
        
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        
        try {
            conn = DatabaseUtil.getConnection();
            String sql = "SELECT id, name, pid, sort FROM wk_wenku_type ORDER BY pid, sort ASC";
            pstmt = conn.prepareStatement(sql);
            rs = pstmt.executeQuery();
            
            List<Map<String, Object>> categories = new ArrayList<>();
            while (rs.next()) {
                Map<String, Object> category = new HashMap<>();
                category.put("id", rs.getInt("id"));
                category.put("name", rs.getString("name"));
                category.put("pid", rs.getInt("pid"));
                category.put("sort", rs.getInt("sort"));
                categories.add(category);
            }
            
            // 直接返回分类列表，让前端自己构建树形结构
            // 使用org.json库创建JSON数组
            JSONArray jsonArray = new JSONArray();
            for (Map<String, Object> category : categories) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("id", category.get("id"));
                jsonObject.put("name", category.get("name"));
                jsonObject.put("pid", category.get("pid"));
                jsonObject.put("sort", category.get("sort"));
                jsonArray.put(jsonObject);
            }
            out.print(jsonArray.toString());
        } catch (Exception e) {
            e.printStackTrace();
            // 返回错误信息
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            JSONObject errorObject = new JSONObject();
            errorObject.put("error", "获取分类失败");
            out.print(errorObject.toString());
        } finally {
            // 关闭连接
            if (rs != null) try { rs.close(); } catch (SQLException e) { e.printStackTrace(); }
            if (pstmt != null) try { pstmt.close(); } catch (SQLException e) { e.printStackTrace(); }
            DatabaseUtil.closeConnection(conn);
        }
    }
}